package com.cqan.controller.account;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cqan.entity.account.Organization;
import com.cqan.service.account.OrganizationService;


/**
 *
 * @author slaton.wu@gmail.com
 * @version 1.0
 * @created 2011-11-6 下午04:05:20
 */
@Controller
@RequestMapping("/org")
public class OrganizationController {
	
	private OrganizationService organizationService;
	
	@RequestMapping("/treeOrg.htm")
	@ResponseBody
	public String getTreeOrg(String pid){
		String hql = "";
		if (pid==null||"".equals(StringUtils.trim(pid))) {
			hql =  "from Organization org where org.status=0 and org.parent IS NULL";
		}else{
			hql = "from Organization org where org.status=0 and org.parent.id='"+pid+"'";
		}
		List<Organization> orgs = organizationService.getList(hql);
		JSONArray array = new JSONArray();
		for (Organization org : orgs) {
			JSONObject obj = changOrgToJson(org);
			array.add(obj);
		}
		return array.toString();
	}
	
	@Autowired
	public void setOrganizationService(OrganizationService organizationService) {
		this.organizationService = organizationService;
	}
	
	
	public JSONObject changOrgToJson(Organization org){
		if(org!=null){
			JSONObject	obj = new JSONObject();
			obj.accumulate("id",org.getId());
			obj.accumulate("text",org.getName());
			obj.accumulate("state","closed");
			if (org.getChildren()!=null&&org.getChildren().size()>0) {
				JSONArray array = new JSONArray();
				for (Organization child : org.getChildren()) {
					array.add(changOrgToJson(child));
				}
				obj.accumulate("children", array);
			}
			return obj;
		}
		return null;
	}

}
